<template>
  <view class="add-planting-container">
    <view class="header">
      <roc-icon-plus type="fas" name="arrow-left" :size="20" color="#333" @click="goBack"></roc-icon-plus>
      <text class="title">{{ isEdit ? '编辑播种' : '播种管理' }}</text>
      <view class="save-btn" @click="submitForm">保存</view>
    </view>
    
    <view class="form-content">
      <!-- 播种时间 -->
      <view class="form-item">
        <view class="form-label">
          播种时间
          <text class="required">*</text>
        </view>
        <view class="form-input date-picker">
          <uni-datetime-picker
            type="datetime"
            v-model="formData.plantingDate"
            :border="false"
            @change="dateChange"
          >
            <template v-slot:default>
              <view class="uni-date-picker-container">
                <text :class="{ placeholder: !formData.plantingDateFormatted }">{{ formData.plantingDateFormatted || '-/-/-' }}</text>
                <roc-icon-plus type="fas" name="calendar-alt" :size="18" color="#999"></roc-icon-plus>
              </view>
            </template>
          </uni-datetime-picker>
        </view>
      </view>
      
      <!-- 地块 -->
      <view class="form-item">
        <view class="form-label">
          地块
          <text class="required">*</text>
        </view>
        <view class="form-input select-picker" @click="showLandBlocks">
          <text :class="{ placeholder: !formData.landBlock }">{{ formData.landBlock || '请选择地块' }}</text>
          <roc-icon-plus type="fas" name="chevron-down" :size="18" color="#999"></roc-icon-plus>
        </view>
      </view>
      
      <!-- 条田编号 -->
      <view class="form-item">
        <view class="form-label">
          条田编号
          <text class="required">*</text>
        </view>
        <view class="form-input radio-group">
          <view class="radio-options">
            <view 
              class="radio-option" 
              :class="{ active: formData.fieldOption === '全选' }"
              @click="selectFieldOption('全选')"
            >全选</view>
            <view 
              class="radio-option" 
              :class="{ active: formData.fieldOption === '清空' }"
              @click="selectFieldOption('清空')"
            >清空</view>
          </view>
          
          <view class="field-list">
            <view 
              class="field-item" 
              v-for="(field, index) in availableFields" 
              :key="index"
              :class="{ active: formData.selectedFields.includes(field) }"
              @click="toggleField(field)"
            >
              {{ field }}
            </view>
          </view>
        </view>
      </view>
      
      <!-- 农作物类型 -->
      <view class="form-item">
        <view class="form-label">
          农作物类型
          <text class="required">*</text>
        </view>
        <view class="form-input select-picker" @click="showCropTypes">
          <text :class="{ placeholder: !formData.cropType }">{{ formData.cropType || '请选择农作物类型' }}</text>
          <roc-icon-plus type="fas" name="chevron-down" :size="18" color="#999"></roc-icon-plus>
        </view>
      </view>
      
      <!-- 种子名称 -->
      <view class="form-item">
        <view class="form-label">
          种子名称
          <text class="required">*</text>
        </view>
        <view class="form-input select-picker" @click="showSeedNames">
          <text :class="{ placeholder: !formData.seedName }">{{ formData.seedName || '请选择种子品种' }}</text>
          <roc-icon-plus type="fas" name="chevron-down" :size="18" color="#999"></roc-icon-plus>
        </view>
      </view>
      
      <!-- 播种面积 -->
      <view class="form-item">
        <view class="form-label">
          播种面积
          <text class="required">*</text>
        </view>
        <view class="form-input number-input">
          <input type="digit" v-model="formData.area" placeholder="请输入播种面积" />
          <text class="unit">亩</text>
        </view>
      </view>
      
      <!-- 负责人 -->
      <view class="form-item">
        <view class="form-label">
          负责人
          <text class="required">*</text>
        </view>
        <view class="form-input">
          <input type="text" v-model="formData.manager" placeholder="请输入负责人姓名" />
        </view>
      </view>
      
      <!-- 播种方式 -->
      <view class="form-item">
        <view class="form-label">
          播种方式
          <text class="required">*</text>
        </view>
        <view class="form-input method-selector">
          <view class="method-row">
            <view 
              class="method-item" 
              :class="{ active: formData.plantingMethod === '水直播' }"
              @click="selectMethod('水直播')"
            >
              <view class="method-icon water">
                <roc-icon-plus type="fas" name="water" :size="22" color="#4fc3f7"></roc-icon-plus>
              </view>
              <text>水直播</text>
            </view>
            <view 
              class="method-item" 
              :class="{ active: formData.plantingMethod === '旱直播' }"
              @click="selectMethod('旱直播')"
            >
              <view class="method-icon dry">
                <roc-icon-plus type="fas" name="seedling" :size="22" color="#66bb6a"></roc-icon-plus>
              </view>
              <text>旱直播</text>
            </view>
            <view 
              class="method-item" 
              :class="{ active: formData.plantingMethod === '插秧' }"
              @click="selectMethod('插秧')"
            >
              <view class="method-icon transplant">
                <roc-icon-plus type="fas" name="seedling" :size="22" color="#ff9800"></roc-icon-plus>
              </view>
              <text>插秧</text>
            </view>
          </view>
        </view>
      </view>
      
      <!-- 播种工具 -->
      <view class="form-item" v-if="formData.plantingMethod">
        <view class="form-label">
          播种工具
          <text class="required">*</text>
        </view>
        <view class="form-input method-selector">
          <view class="method-row">
            <view 
              class="method-item" 
              :class="{ active: formData.plantingTool === '无人机' }"
              @click="selectTool('无人机')"
            >
              <view class="method-icon drone">
                <roc-icon-plus type="fas" name="drone" :size="22" color="#9c27b0"></roc-icon-plus>
              </view>
              <text>无人机</text>
            </view>
            <view 
              class="method-item" 
              :class="{ active: formData.plantingTool === '机械' }"
              @click="selectTool('机械')"
            >
              <view class="method-icon machine">
                <roc-icon-plus type="fas" name="tractor" :size="22" color="#f44336"></roc-icon-plus>
              </view>
              <text>机械</text>
            </view>
          </view>
        </view>
      </view>
      
      <!-- 播种照片 -->
      <view class="form-item">
        <view class="form-label">播种照片</view>
        <view class="form-input upload-area">
          <view class="upload-box" @click="uploadImage">
            <view class="upload-icon">
              <roc-icon-plus type="fas" name="camera" :size="30" color="#cccccc"></roc-icon-plus>
            </view>
            <text class="upload-text">添加照片</text>
          </view>
          <view class="image-preview" v-for="(img, index) in formData.images" :key="index">
            <image :src="img" mode="aspectFill"></image>
            <view class="delete-image" @click.stop="removeImage(index)">
              <roc-icon-plus type="fas" name="times-circle" :size="16" color="#ffffff"></roc-icon-plus>
            </view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      isEdit: false,
      editId: null,
      formData: {
        plantingDate: '', // 日期选择器使用的格式 (yyyy-MM-dd HH:mm)
        plantingDateFormatted: '', // 显示用的格式 (yyyy年MM月dd日 HH:mm)
        landBlock: '',
        fieldOption: '',
        selectedFields: [],
        cropType: '',
        seedName: '',
        area: '',
        manager: '',
        plantingMethod: '',
        plantingTool: '',
        images: []
      },
      landBlocks: ['一号地块', '二号地块', '三号地块', '四号地块'],
      availableFields: ['A区', 'B区', 'C区', 'D区', 'E区', 'F区', 'G区', 'H区'],
      cropTypes: ['水稻', '小麦', '玉米', '大豆'],
      seedNames: {
        '水稻': ['中早39', '粳稻102', '丰优香占'],
        '小麦': ['中麦175', '郑麦366', '扬麦23'],
        '玉米': ['郑单958', '先玉335', '德美亚'],
        '大豆': ['中黄13', '黄泡1号', '绥农14']
      }
    }
  },
  onLoad(options) {
    if (options.id) {
      this.isEdit = true;
      this.editId = parseInt(options.id);
      this.loadPlantingData(this.editId);
    }
  },
  methods: {
    goBack() {
      uni.navigateBack();
    },
    loadPlantingData(id) {
      // 在实际应用中，这里应该从API获取数据
      // 这里模拟加载编辑数据
      const plantingData = this.getMockPlantingData(id);
      if (plantingData) {
        // 解析日期和时间
        const dateMatch = plantingData.date.match(/(\d{4})年(\d{1,2})月(\d{1,2})日/);
        let dateFormatted = '';
        if (dateMatch) {
          const year = dateMatch[1];
          const month = dateMatch[2].padStart(2, '0');
          const day = dateMatch[3].padStart(2, '0');
          dateFormatted = `${year}-${month}-${day} ${plantingData.time}`;
        }
        
        // 解析作物和种子
        const cropInfo = plantingData.crop.split('/');
        const cropType = cropInfo[0] || '';
        const seedName = cropInfo[1] || '';
        
        // 解析播种方式
        const methodInfo = plantingData.method.split('-');
        const plantingMethod = methodInfo[0] || '';
        const plantingTool = methodInfo[1] || '';
        
        this.formData = {
          plantingDate: dateFormatted,
          plantingDateFormatted: `${plantingData.date} ${plantingData.time}`,
          landBlock: plantingData.land,
          fieldOption: '',
          selectedFields: ['A区', 'B区'],  // 模拟数据
          cropType,
          seedName,
          area: plantingData.area.toString(),
          manager: '张明',  // 模拟数据
          plantingMethod,
          plantingTool,
          images: []  // 模拟数据
        };
      }
    },
    getMockPlantingData(id) {
      const mockData = [
        {
          id: 1,
          date: '2023年10月15日',
          time: '08:30',
          land: '一号地块',
          crop: '冬小麦/中麦175',
          area: 15.6,
          method: '水直播-无人机'
        },
        {
          id: 2,
          date: '2023年10月12日',
          time: '14:15',
          land: '二号地块',
          crop: '玉米/郑单958',
          area: 23.2,
          method: '水直播-机械'
        },
        {
          id: 3,
          date: '2023年10月8日',
          time: '09:45',
          land: '三号地块',
          crop: '水稻/中早39',
          area: 18.7,
          method: '插秧-机械'
        },
        {
          id: 4,
          date: '2023年10月5日',
          time: '10:30',
          land: '四号地块',
          crop: '大豆/中黄13',
          area: 12.5,
          method: '插秧-机械'
        }
      ];
      return mockData.find(item => item.id === id);
    },
    dateChange(e) {
      if (e) {
        const date = new Date(e);
        const year = date.getFullYear();
        const month = date.getMonth() + 1;
        const day = date.getDate();
        const hours = date.getHours();
        const minutes = date.getMinutes();
        
        // 格式化时间
        const formattedHours = hours.toString().padStart(2, '0');
        const formattedMinutes = minutes.toString().padStart(2, '0');
        
        this.formData.plantingDateFormatted = `${year}年${month}月${day}日 ${formattedHours}:${formattedMinutes}`;
      } else {
        this.formData.plantingDateFormatted = '';
      }
    },
    showLandBlocks() {
      uni.showActionSheet({
        itemList: this.landBlocks,
        success: (res) => {
          this.formData.landBlock = this.landBlocks[res.tapIndex];
        }
      });
    },
    selectFieldOption(option) {
      this.formData.fieldOption = option;
      
      if (option === '全选') {
        this.formData.selectedFields = [...this.availableFields];
      } else if (option === '清空') {
        this.formData.selectedFields = [];
      }
    },
    toggleField(field) {
      const index = this.formData.selectedFields.indexOf(field);
      if (index === -1) {
        this.formData.selectedFields.push(field);
      } else {
        this.formData.selectedFields.splice(index, 1);
      }
      
      // 重置全选/清空状态
      this.formData.fieldOption = '';
    },
    showCropTypes() {
      uni.showActionSheet({
        itemList: this.cropTypes,
        success: (res) => {
          const selectedCropType = this.cropTypes[res.tapIndex];
          this.formData.cropType = selectedCropType;
          this.formData.seedName = ''; // 清空种子选择
        }
      });
    },
    showSeedNames() {
      if (!this.formData.cropType) {
        uni.showToast({
          title: '请先选择农作物类型',
          icon: 'none'
        });
        return;
      }
      
      const availableSeeds = this.seedNames[this.formData.cropType] || [];
      
      if (availableSeeds.length === 0) {
        uni.showToast({
          title: '当前作物没有可用种子',
          icon: 'none'
        });
        return;
      }
      
      uni.showActionSheet({
        itemList: availableSeeds,
        success: (res) => {
          this.formData.seedName = availableSeeds[res.tapIndex];
        }
      });
    },
    selectMethod(method) {
      this.formData.plantingMethod = method;
      // 切换播种方式时清空已选工具
      this.formData.plantingTool = '';
    },
    selectTool(tool) {
      this.formData.plantingTool = tool;
    },
    uploadImage() {
      uni.chooseImage({
        count: 1,
        success: (res) => {
          this.formData.images.push(res.tempFilePaths[0]);
        }
      });
    },
    removeImage(index) {
      this.formData.images.splice(index, 1);
    },
    validateForm() {
      if (!this.formData.plantingDate) {
        uni.showToast({
          title: '请选择播种时间',
          icon: 'none'
        });
        return false;
      }
      
      if (!this.formData.landBlock) {
        uni.showToast({
          title: '请选择地块',
          icon: 'none'
        });
        return false;
      }
      
      if (this.formData.selectedFields.length === 0) {
        uni.showToast({
          title: '请选择条田编号',
          icon: 'none'
        });
        return false;
      }
      
      if (!this.formData.cropType) {
        uni.showToast({
          title: '请选择农作物类型',
          icon: 'none'
        });
        return false;
      }
      
      if (!this.formData.seedName) {
        uni.showToast({
          title: '请选择种子名称',
          icon: 'none'
        });
        return false;
      }
      
      if (!this.formData.area || isNaN(parseFloat(this.formData.area)) || parseFloat(this.formData.area) <= 0) {
        uni.showToast({
          title: '请输入有效的播种面积',
          icon: 'none'
        });
        return false;
      }
      
      if (!this.formData.manager) {
        uni.showToast({
          title: '请输入负责人',
          icon: 'none'
        });
        return false;
      }
      
      if (!this.formData.plantingMethod) {
        uni.showToast({
          title: '请选择播种方式',
          icon: 'none'
        });
        return false;
      }
      
      if (!this.formData.plantingTool) {
        uni.showToast({
          title: '请选择播种工具',
          icon: 'none'
        });
        return false;
      }
      
      return true;
    },
    submitForm() {
      if (!this.validateForm()) {
        return;
      }
      
      // 构建提交的数据对象
      const submitData = {
        id: this.isEdit ? this.editId : new Date().getTime(),
        date: this.formData.plantingDateFormatted.split(' ')[0],
        time: this.formData.plantingDateFormatted.split(' ')[1],
        land: this.formData.landBlock,
        fields: this.formData.selectedFields.join(','),
        crop: `${this.formData.cropType}/${this.formData.seedName}`,
        area: parseFloat(this.formData.area),
        manager: this.formData.manager,
        method: `${this.formData.plantingMethod}-${this.formData.plantingTool}`,
        images: this.formData.images
      };
      
      // 在实际应用中，这里应该调用API提交数据
      // 这里简化处理，显示成功提示并返回
      uni.showLoading({
        title: '提交中...'
      });
      
      setTimeout(() => {
        uni.hideLoading();
        uni.showToast({
          title: this.isEdit ? '修改成功' : '添加成功',
          icon: 'success',
          duration: 2000,
          success: () => {
            setTimeout(() => {
              // 返回上一页并刷新
              uni.navigateBack();
            }, 1500);
          }
        });
      }, 1000);
    }
  }
}
</script>

<style lang="scss">
.add-planting-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  
  .header {
    height: 100rpx;
    display: flex;
    align-items: center;
    padding: 0 30rpx;
    background-color: #fff;
    box-shadow: 0 2rpx 10rpx rgba(0,0,0,0.05);
    
    .title {
      flex: 1;
      text-align: center;
      font-size: 36rpx;
      font-weight: bold;
      color: #333;
    }
    
    .save-btn {
      font-size: 28rpx;
      color: #5654e8;
    }
  }
  
  .form-content {
    background-color: #fff;
    margin-top: 20rpx;
    
    .form-item {
      padding: 30rpx;
      border-bottom: 1rpx solid #f0f0f0;
      
      .form-label {
        font-size: 28rpx;
        color: #333;
        margin-bottom: 20rpx;
        font-weight: 500;
        
        .required {
          color: #f44336;
          margin-left: 6rpx;
        }
      }
      
      .form-input {
        position: relative;
        
        input, textarea {
          width: 100%;
          height: 80rpx;
          font-size: 28rpx;
          color: #333;
          padding: 0 20rpx;
          border: 1rpx solid #eaeaea;
          border-radius: 8rpx;
        }
        
        textarea {
          height: 160rpx;
          padding: 20rpx;
        }
        
        .placeholder {
          color: #999;
        }
        
        .unit {
          position: absolute;
          right: 20rpx;
          top: 50%;
          transform: translateY(-50%);
          color: #999;
          font-size: 28rpx;
        }
      }
      
      .date-picker, .select-picker {
        display: flex;
        align-items: center;
        justify-content: space-between;
        height: 80rpx;
        padding: 0 20rpx;
        border: 1rpx solid #eaeaea;
        border-radius: 8rpx;
        font-size: 28rpx;
        color: #333;
        
        .uni-date-picker-container {
          width: 100%;
          display: flex;
          justify-content: space-between;
          align-items: center;
        }
      }
      
      .number-input {
        input {
          padding-right: 60rpx;
        }
      }
      
      .radio-group {
        .radio-options {
          display: flex;
          margin-bottom: 20rpx;
          
          .radio-option {
            padding: 12rpx 24rpx;
            background-color: #f5f5f5;
            border-radius: 8rpx;
            font-size: 26rpx;
            color: #666;
            margin-right: 20rpx;
            
            &.active {
              background-color: #e6e5ff;
              color: #5654e8;
            }
          }
        }
        
        .field-list {
          display: flex;
          flex-wrap: wrap;
          
          .field-item {
            width: 120rpx;
            height: 70rpx;
            display: flex;
            align-items: center;
            justify-content: center;
            background-color: #f5f5f5;
            border-radius: 8rpx;
            font-size: 26rpx;
            color: #666;
            margin-right: 20rpx;
            margin-bottom: 20rpx;
            
            &.active {
              background-color: #e6e5ff;
              color: #5654e8;
            }
          }
        }
      }
      
      .method-selector {
        .method-row {
          display: flex;
          
          .method-item {
            display: flex;
            flex-direction: column;
            align-items: center;
            margin-right: 40rpx;
            
            .method-icon {
              width: 80rpx;
              height: 80rpx;
              border-radius: 50%;
              display: flex;
              align-items: center;
              justify-content: center;
              margin-bottom: 10rpx;
              
              &.water {
                background-color: #e3f2fd;
              }
              
              &.dry {
                background-color: #e8f5e9;
              }
              
              &.transplant {
                background-color: #fff3e0;
              }
              
              &.drone {
                background-color: #f3e5f5;
              }
              
              &.machine {
                background-color: #ffebee;
              }
            }
            
            text {
              font-size: 26rpx;
              color: #666;
            }
            
            &.active {
              .method-icon {
                border: 2rpx solid #5654e8;
              }
              
              text {
                color: #5654e8;
              }
            }
          }
        }
      }
      
      .upload-area {
        display: flex;
        flex-wrap: wrap;
        
        .upload-box {
          width: 160rpx;
          height: 160rpx;
          background-color: #f5f5f5;
          border-radius: 8rpx;
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;
          margin-right: 20rpx;
          margin-bottom: 20rpx;
          
          .upload-text {
            font-size: 24rpx;
            color: #999;
            margin-top: 10rpx;
          }
        }
        
        .image-preview {
          width: 160rpx;
          height: 160rpx;
          border-radius: 8rpx;
          overflow: hidden;
          position: relative;
          margin-right: 20rpx;
          margin-bottom: 20rpx;
          
          image {
            width: 100%;
            height: 100%;
          }
          
          .delete-image {
            position: absolute;
            top: 6rpx;
            right: 6rpx;
            width: 36rpx;
            height: 36rpx;
            background-color: rgba(0, 0, 0, 0.5);
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
          }
        }
      }
    }
  }
}
</style> 